package com.example.controller;

import com.example.model.Equipment;
import com.example.model.Inventory;
import com.example.model.LaundryOrder;
import com.example.model.User;
import com.example.model.WashService;
import com.example.service.EquipmentService;
import com.example.service.InventoryService;
import com.example.service.LaundryOrderService;
import com.example.service.UserService;
import com.example.service.WashServiceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/wash")
@Tag(name = "洗护业务API", description = "洗护业务相关的API接口")
public class WashApiController {

    @Autowired
    private WashServiceService washServiceService;

    @Autowired
    private LaundryOrderService laundryOrderService;

    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private UserService userService;

    // ==================== 洗护服务管理 ====================






    // ==================== 洗护订单管理 ====================
    @GetMapping("/orders")
    @Operation(summary = "获取洗护订单列表")
    public ResponseEntity<Page<LaundryOrder>> getWashOrders(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createdAt") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) Long customerId,
            @RequestParam(required = false) Long workerId) {
        
        Sort sort = Sort.by(Sort.Direction.fromString(sortDir), sortBy);
        Pageable pageable = PageRequest.of(page, size, sort);
        
        Page<LaundryOrder> orders = laundryOrderService.getAllOrders(pageable);
        return ResponseEntity.ok(orders);
    }

    @PostMapping("/orders")
    @Operation(summary = "创建洗护订单")
    public ResponseEntity<LaundryOrder> createWashOrder(@Valid @RequestBody LaundryOrder order) {
        LaundryOrder createdOrder = laundryOrderService.createOrder(order);
        return ResponseEntity.ok(createdOrder);
    }

    @GetMapping("/orders/{id}")
    @Operation(summary = "获取洗护订单详情")
    public ResponseEntity<LaundryOrder> getWashOrderDetail(@PathVariable Long id) {
        return laundryOrderService.getOrderById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/orders/{id}")
    @Operation(summary = "更新洗护订单")
    public ResponseEntity<LaundryOrder> updateWashOrder(
            @PathVariable Long id,
            @Valid @RequestBody LaundryOrder order) {
        
        return laundryOrderService.getOrderById(id)
                .map(existingOrder -> {
                    order.setId(id);
                    LaundryOrder updatedOrder = laundryOrderService.updateOrder(order);
                    return ResponseEntity.ok(updatedOrder);
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/orders/{id}/status")
    @Operation(summary = "更新订单状态")
    public ResponseEntity<Map<String, Object>> updateOrderStatus(
            @PathVariable Long id,
            @RequestBody Map<String, String> statusData) {
        
        String status = statusData.get("status");
        String notes = statusData.get("notes");
        
        // 这里应该实现订单状态更新逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "订单状态更新成功");
        
        return ResponseEntity.ok(response);
    }

    @PutMapping("/orders/{id}/cancel")
    @Operation(summary = "取消订单")
    public ResponseEntity<Map<String, Object>> cancelOrder(
            @PathVariable Long id,
            @RequestBody Map<String, String> cancelData) {
        
        String reason = cancelData.get("reason");
        
        // 这里应该实现取消订单的逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "订单已取消");
        
        return ResponseEntity.ok(response);
    }

    @PutMapping("/orders/{id}/assign")
    @Operation(summary = "分配工人")
    public ResponseEntity<Map<String, Object>> assignWorker(
            @PathVariable Long id,
            @RequestBody Map<String, Object> assignData) {
        
        Long workerId = ((Number) assignData.get("workerId")).longValue();
        
        // 这里应该实现分配工人的逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "工人分配成功");
        
        return ResponseEntity.ok(response);
    }





    // ==================== 洗护工人管理 ====================
    @GetMapping("/workers")
    @Operation(summary = "获取工人列表")
    public ResponseEntity<Page<User>> getWorkerList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "username") String sortBy,
            @RequestParam(defaultValue = "asc") String sortDir,
            @RequestParam(required = false) String status) {
        
        Sort sort = Sort.by(Sort.Direction.fromString(sortDir), sortBy);
        Pageable pageable = PageRequest.of(page, size, sort);
        
        // 这里应该过滤出工人角色的用户
        Page<User> workers = userService.getAllUsers(pageable);
        return ResponseEntity.ok(workers);
    }

    @PostMapping("/workers")
    @Operation(summary = "创建工人")
    public ResponseEntity<User> createWorker(@Valid @RequestBody User worker) {
        // 设置工人角色
        worker.setRole(User.UserRole.WORKER);
        User createdWorker = userService.createUser(worker);
        return ResponseEntity.ok(createdWorker);
    }

    @GetMapping("/workers/{id}")
    @Operation(summary = "获取工人详情")
    public ResponseEntity<User> getWorkerDetail(@PathVariable Long id) {
        return userService.getUserById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/workers/{id}")
    @Operation(summary = "更新工人信息")
    public ResponseEntity<User> updateWorker(
            @PathVariable Long id,
            @Valid @RequestBody User worker) {
        
        return userService.getUserById(id)
                .map(existingWorker -> {
                    worker.setId(id);
                    User updatedWorker = userService.updateUser(worker);
                    return ResponseEntity.ok(updatedWorker);
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/workers/{id}/status")
    @Operation(summary = "更新工人状态")
    public ResponseEntity<Map<String, Object>> updateWorkerStatus(
            @PathVariable Long id,
            @RequestBody Map<String, String> statusData) {
        
        String status = statusData.get("status");
        
        // 这里应该实现工人状态更新逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "工人状态更新成功");
        
        return ResponseEntity.ok(response);
    }

    // ==================== 洗护客户管理 ====================
    @GetMapping("/customers")
    @Operation(summary = "获取客户列表")
    public ResponseEntity<Page<User>> getCustomerList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "username") String sortBy,
            @RequestParam(defaultValue = "asc") String sortDir) {
        
        Sort sort = Sort.by(Sort.Direction.fromString(sortDir), sortBy);
        Pageable pageable = PageRequest.of(page, size, sort);
        
        // 这里应该过滤出客户角色的用户
        Page<User> customers = userService.getAllUsers(pageable);
        return ResponseEntity.ok(customers);
    }

    @GetMapping("/customers/{id}")
    @Operation(summary = "获取客户详情")
    public ResponseEntity<User> getCustomerDetail(@PathVariable Long id) {
        return userService.getUserById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/customers/{id}/orders")
    @Operation(summary = "获取客户订单")
    public ResponseEntity<Page<LaundryOrder>> getCustomerOrders(
            @PathVariable Long id,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
        
        return userService.getUserById(id)
                .map(customer -> {
                    Page<LaundryOrder> orders = laundryOrderService.findByCustomer(customer, pageable);
                    return ResponseEntity.ok(orders);
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping("/customers/{id}/notes")
    @Operation(summary = "添加客户备注")
    public ResponseEntity<Map<String, Object>> addCustomerNote(
            @PathVariable Long id,
            @RequestBody Map<String, String> noteData) {
        
        String note = noteData.get("note");
        
        // 这里应该实现添加客户备注的逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "客户备注添加成功");
        
        return ResponseEntity.ok(response);
    }

    // ==================== 洗护统计 ====================
    @GetMapping("/statistics")
    @Operation(summary = "获取洗护统计数据")
    public ResponseEntity<Map<String, Object>> getWashStatistics() {
        Map<String, Object> statistics = new HashMap<>();

        // 基础统计
        statistics.put("totalOrders", laundryOrderService.countTotalOrders());
        statistics.put("totalServices", washServiceService.countActiveServices());
        statistics.put("totalEquipment", equipmentService.countTotalEquipment());
        statistics.put("totalCustomers", userService.countTotalUsers());

        // 今日统计
        statistics.put("todayOrders", 25);
        statistics.put("todayRevenue", 3500.0);
        statistics.put("todayCompletedOrders", 22);

        // 设备状态统计
        statistics.put("equipmentStats", Map.of(
            "available", equipmentService.countByStatus(Equipment.EquipmentStatus.AVAILABLE),
            "inUse", equipmentService.countByStatus(Equipment.EquipmentStatus.IN_USE),
            "maintenance", equipmentService.countByStatus(Equipment.EquipmentStatus.MAINTENANCE)
        ));

        return ResponseEntity.ok(statistics);
    }

    @GetMapping("/dashboard/stats")
    @Operation(summary = "获取仪表盘统计数据")
    public ResponseEntity<Map<String, Object>> getDashboardStats() {
        Map<String, Object> stats = new HashMap<>();

        // 核心指标
        stats.put("totalOrders", 1250);
        stats.put("monthlyRevenue", 85000.0);
        stats.put("activeCustomers", 450);
        stats.put("completionRate", 96.5);

        // 趋势数据
        stats.put("orderTrend", List.of(120, 135, 148, 162, 155, 170, 185));
        stats.put("revenueTrend", List.of(8500, 9200, 8800, 9500, 10200, 9800, 10500));

        return ResponseEntity.ok(stats);
    }

    @GetMapping("/statistics/orders")
    @Operation(summary = "获取订单统计")
    public ResponseEntity<Map<String, Object>> getOrderStatistics(
            @RequestParam(required = false) String period,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {

        Map<String, Object> orderStats = new HashMap<>();

        // 订单状态统计
        orderStats.put("statusStats", Map.of(
            "pending", 15,
            "processing", 25,
            "completed", 180,
            "cancelled", 5
        ));

        // 服务类型统计
        orderStats.put("serviceStats", Map.of(
            "dryClean", 85,
            "wetClean", 95,
            "ironing", 45,
            "repair", 12
        ));

        // 时间趋势
        orderStats.put("timeTrend", List.of(
            Map.of("date", "2024-11-01", "orders", 25, "revenue", 3500.0),
            Map.of("date", "2024-11-02", "orders", 30, "revenue", 4200.0),
            Map.of("date", "2024-11-03", "orders", 28, "revenue", 3900.0)
        ));

        return ResponseEntity.ok(orderStats);
    }

    @GetMapping("/statistics/revenue")
    @Operation(summary = "获取营收统计")
    public ResponseEntity<Map<String, Object>> getRevenueStatistics(
            @RequestParam(required = false) String period,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {

        Map<String, Object> revenueStats = new HashMap<>();

        // 营收概览
        revenueStats.put("totalRevenue", 125000.0);
        revenueStats.put("monthlyRevenue", 85000.0);
        revenueStats.put("dailyAverage", 2800.0);
        revenueStats.put("growthRate", 15.5);

        // 营收来源
        revenueStats.put("revenueByService", Map.of(
            "dryClean", 45000.0,
            "wetClean", 35000.0,
            "ironing", 15000.0,
            "repair", 8000.0
        ));

        // 营收趋势
        revenueStats.put("revenueTrend", List.of(
            Map.of("month", "2024-07", "revenue", 72000.0),
            Map.of("month", "2024-08", "revenue", 78000.0),
            Map.of("month", "2024-09", "revenue", 82000.0),
            Map.of("month", "2024-10", "revenue", 85000.0),
            Map.of("month", "2024-11", "revenue", 88000.0)
        ));

        return ResponseEntity.ok(revenueStats);
    }

    @GetMapping("/statistics/equipment")
    @Operation(summary = "获取设备统计")
    public ResponseEntity<Map<String, Object>> getEquipmentStatistics() {
        Map<String, Object> equipmentStats = new HashMap<>();

        // 设备状态统计
        equipmentStats.put("statusStats", equipmentService.getEquipmentStatisticsByStatus());

        // 设备类型统计
        equipmentStats.put("typeStats", equipmentService.getEquipmentStatisticsByType());

        // 设备利用率
        equipmentStats.put("utilizationRate", Map.of(
            "washingMachine", 85.5,
            "dryer", 78.2,
            "dryCleaningMachine", 92.1,
            "ironingMachine", 65.8
        ));

        // 维护统计
        equipmentStats.put("maintenanceStats", Map.of(
            "needingMaintenance", equipmentService.findEquipmentNeedingMaintenance().size(),
            "lastMonthMaintenance", 5,
            "averageDowntime", 2.5
        ));

        return ResponseEntity.ok(equipmentStats);
    }

    @GetMapping("/statistics/workers")
    @Operation(summary = "获取工人统计")
    public ResponseEntity<Map<String, Object>> getWorkerStatistics() {
        Map<String, Object> workerStats = new HashMap<>();

        // 工人概览
        workerStats.put("totalWorkers", 12);
        workerStats.put("activeWorkers", 10);
        workerStats.put("onlineWorkers", 8);

        // 工人绩效
        workerStats.put("performance", List.of(
            Map.of("workerId", 1L, "name", "张师傅", "completedOrders", 45, "rating", 4.8),
            Map.of("workerId", 2L, "name", "李师傅", "completedOrders", 38, "rating", 4.6),
            Map.of("workerId", 3L, "name", "王师傅", "completedOrders", 42, "rating", 4.7)
        ));

        // 工作量分布
        workerStats.put("workloadDistribution", Map.of(
            "dryClean", 35,
            "wetClean", 40,
            "ironing", 20,
            "repair", 5
        ));

        return ResponseEntity.ok(workerStats);
    }
}
